package com.zone.core.helper

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.fragment.app.Fragment
import com.zone.core.R
import com.zone.core.model.PermissionRequestModel
import org.jetbrains.anko.toast
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions


/**
 *Author: last
 *Time: 2024-02-13
 *Description: 权限申请辅助类
 */
object PermissionHelper {
    private val TAG = "PermissionHelper"
    private val permissionsRequests = ArrayList<PermissionRequestModel>()

    private val permissionsMap = mapOf(
        Manifest.permission.CAMERA to "相机",
        Manifest.permission.READ_EXTERNAL_STORAGE to "读取外部存储",
        Manifest.permission.WRITE_EXTERNAL_STORAGE to "写入外部存储",
        Manifest.permission.ACCESS_FINE_LOCATION to "访问位置信息",
        Manifest.permission.READ_PHONE_STATE to "读取手机状态",
        Manifest.permission.READ_CONTACTS to "读取联系人",
    )

    //权限集合
    val permissionsMultiple = arrayOf(
        Manifest.permission.CAMERA,//相机
        Manifest.permission.READ_EXTERNAL_STORAGE,//读取外部存储
        Manifest.permission.WRITE_EXTERNAL_STORAGE,//写入外部存储
        Manifest.permission.ACCESS_FINE_LOCATION,//访问精确位置信息
        Manifest.permission.READ_PHONE_STATE,//读取手机状态
        Manifest.permission.READ_CONTACTS,//读取联系人
    )

    private fun addPermissionRequest(permissionRequestModel: PermissionRequestModel) {
        permissionsRequests.add(permissionRequestModel)
    }

    /**
     * 权限拒绝的处理
     */
    private fun onDenied(requestCode: Int, perms: List<String>) {
        val requestModel = getRequestModel(requestCode)
        requestModel?.let {
            it.permissions.removeAll(perms)
            if (it.permissions.isEmpty()) {
                it.onDenied.invoke()
                permissionsRequests.remove(it)
            }
        }
    }

    /**
     * 权限拒绝的处理
     */
    private fun onDenied(requestCode: Int) {
        val requestModel = getRequestModel(requestCode)
        requestModel?.let {
            it.onDenied.invoke()
            permissionsRequests.remove(it)
        }
    }

    /**
     * 权限申请失败
     */
    fun onPermissionsDenied(activity: Activity, requestCode: Int, perms: MutableList<String>) {
        getRequestModel(requestCode)?.let {

            //用户选择了不再提醒则引导用户去设置界面开启权限
            if (EasyPermissions.somePermissionPermanentlyDenied(activity, perms)) {
                Log.d(TAG, "被设置了不再提醒的权限: $perms")
                AppSettingsDialog.Builder(activity)
                    .setRequestCode(requestCode)
                    .setTitle("功能受限")
                    .setRationale(
                        "请手动开启权限：${
                            permissionsMap.filterKeys { it in perms }.values.joinToString(
                                separator = "、"
                            )
                        }"
                    )
                    .setNegativeButton("关闭")
                    .setPositiveButton("打开")
                    .setOpenInNewTask(true)
                    .build().show()
            } else {
                onDenied(requestCode, perms)
            }
        }
    }

    /**
     * 权限申请失败
     */
    fun onPermissionsDenied(fragment: Fragment, requestCode: Int, perms: MutableList<String>) {
        getRequestModel(requestCode)?.let {
            //用户选择了不再提醒则引导用户去设置界面开启权限
            if (EasyPermissions.somePermissionPermanentlyDenied(fragment, perms)) {
                AppSettingsDialog.Builder(fragment)
                    .setRequestCode(requestCode)
                    .build().show()
            } else {
                onDenied(requestCode, perms)
            }
        }

    }

    /**
     * 权限申请成功
     */
    fun onGranted(requestCode: Int, perms: List<String>) {
        val requestModel = getRequestModel(requestCode)
        requestModel?.let {
            it.permissions.removeAll(perms)
            if (it.permissions.isEmpty()) {
                it.onGranted.invoke()
                permissionsRequests.remove(it)
            }
        }
    }


    /**
     * 用户选择了拒绝不再提醒后引导去设置界面开启权限后返回界面的处理
     */
    fun onActivityResult(context: Context, requestCode: Int, resultCode: Int, data: Intent?) {
        //判断设置返回后权限是否开启
        getRequestModel(requestCode)?.let {
            if (EasyPermissions.hasPermissions(context, *it.permissions.toTypedArray())) {
                onGranted(requestCode, it.permissions)
            } else {
                onDenied(requestCode)
            }
        }
    }

    private fun getRequestModel(requestCode: Int) =
        permissionsRequests.find { it.requestCode == requestCode }

    fun requestPermissions(
        activity: Activity,
        permissions: Array<out String>,
        onGranted: () -> Unit,
        onDenied: (() -> Unit)?
    ) {
        activity.let {
            if (EasyPermissions.hasPermissions(it, *permissions)) {
                onGranted()
            } else {
                val requestModel = PermissionRequestModel(
                    mutableListOf(*permissions),
                    onDenied ?: { defaultDeniedHandle(it) },
                    onGranted
                )
                addPermissionRequest(requestModel)
                EasyPermissions.requestPermissions(
                    activity,
                    it.getString(R.string.permission_request_hint),
                    requestModel.requestCode,
                    *permissions
                )
            }
        }
    }


    /**
     * 默认的权限申请被拒绝的处理
     */
    private fun defaultDeniedHandle(context: Context?) {
        context?.toast("无相应权限可能导致某些功能无法正常使用！")
    }


    /**
     * 权限申请提示弹出框点击拒绝
     */
    fun onRationaleDenied(requestCode: Int) {
        onDenied(requestCode)
    }
}

